package cn.jingzhuan.element.demo.view.util.audio

import android.app.Notification
import android.app.NotificationManager
import android.content.Context.NOTIFICATION_SERVICE
import android.os.Build
import android.support.annotation.RequiresApi

/**
 * Created by KNOX.
 */
abstract class AudioNotificationParent(private val service : AudioService) {

  private var notificationManager : NotificationManager? = null
  private var notifyMode : Int = NOTIFY_MODE_BACKGROUND

  companion object {
    const val NOTIFICATION_ID = 1
    const val NOTIFY_MODE_FOREGROUND = 2
    const val NOTIFY_MODE_BACKGROUND = 3
    const val NOTIFICATION_CHANNEL_ID = "notification"
    private const val TAG = "AudioNotificationParent"
  }

  init {
    notificationManager = service.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      createNotificationChannel()
    }
  }

  abstract fun update()

  fun postNotification(notification : Notification) {
    val newNotifyMode : Int = if (service.isPlaying()) {
      NOTIFY_MODE_FOREGROUND
    } else {
      NOTIFY_MODE_BACKGROUND
    }

    if (newNotifyMode != notifyMode && newNotifyMode == NOTIFY_MODE_BACKGROUND) {
      service.stopForeground(false)
    }

    if (newNotifyMode == NOTIFY_MODE_FOREGROUND) {
      service.startForeground(NOTIFICATION_ID, notification)
    } else {
      notificationManager?.notify(NOTIFICATION_ID, notification)
    }

    notifyMode = newNotifyMode
  }

  fun stop() {
    service.stopForeground(true)
    notificationManager?.cancel(NOTIFICATION_ID)
  }

  @RequiresApi(Build.VERSION_CODES.O)
  private fun createNotificationChannel() {
    var notificationChannel = notificationManager?.getNotificationChannel(NOTIFICATION_CHANNEL_ID)
    if (notificationChannel == null) {
//      notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID,
//          service.getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT).apply {
//        description = service.getString(R.string.app_name)
//        importance = NotificationManager.IMPORTANCE_LOW
//        enableLights(false)
//        enableVibration(false)
//        setShowBadge(false)
//      }
      notificationManager?.createNotificationChannel(notificationChannel)
    }
  }

}